package com.zhongdu.stady.shiro.realm;

import com.zhongdu.stady.pojo.User;
import com.zhongdu.stady.shiro.ELoginType;
import com.zhongdu.stady.token.PhoneToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @ClassNamePhoneRealm
 * @Description
 * @Author ange
 * @Date2019/10/17 14:46
 * @Version V1.0
 **/
@Slf4j
public class PhoneRealm extends AuthorizingRealm {

    /**
     * 授权方法
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 验证方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("手机验证登录 ------ 开始验证");
        PhoneToken phoneToken = (PhoneToken) token;
        //如果等于null登录失败
        if(phoneToken == null) return null;
        //获取手机号和验证码
        Object phone = phoneToken.getUsername();
        char [] code =  phoneToken.getPassword();
        //如果手机号码或验证码为null则登录失败
        if(phone == null || code == null) return null;
        String validCode = String.valueOf(code);
        //如果验证码和手机号有一个不一致则登录失败
        if(!(phone+"").equals("2200106552") || !validCode.equals("1234"))  return null;
        String phoneNum = (String) phone;
        User user = new User();
        user.setPhone(Long.getLong(phoneNum));
        user.setUsername("2200106552");
        user.setPassword("1234");
        log.info("手机验证登录 ----- 登录成功");
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户
                validCode, //密码
                getName()  //realm name
        );
        return authenticationInfo;
    }

    @Override
    public String getName() {
        return ELoginType.PHONE.getType();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        if (token instanceof PhoneToken) {
            return ((PhoneToken) token).getLoginType() == ELoginType.PHONE;
        } else {
            return false;
        }
    }
}